package com.hsgene.shoppingcar.controller.applets;

import com.hsgene.common.RangeType;
import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleStringUtils;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.coupon.dto.GeneticUserDiscountDto;
import com.hsgene.order.domain.applets.AppletsOrderPackageInfoDto;
import com.hsgene.order.domain.applets.AppletsOrderSubmitInfoDto;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.product.dto.wechat.SimpleCommodityDto;
import com.hsgene.product.exception.ProductErrorCode;
import com.hsgene.shoppingcar.domain.GeneticTestingOrderCar;
import com.hsgene.shoppingcar.dto.ConfirmOrderDto;
import com.hsgene.shoppingcar.dto.DiscountDto;
import com.hsgene.shoppingcar.exception.GeneticTestingOrderCarErrorCode;
import com.hsgene.shoppingcar.service.GeneticTestingOrderCarService;
import com.hsgene.shoppingcar.service.api.CommodityService;
import com.hsgene.shoppingcar.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 小程序购物车控制类
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.shoppingcar.controller.applets
 * @author: maodi
 * @createDate: 2018/10/15 9:30
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/users")
public class GeneticTestingOrderCarController {

    private static Logger LOGGER = LogManager.getLogger(GeneticTestingOrderCarController.class);

    @Resource
    GeneticTestingOrderCarService geneticTestingOrderCarService;

    @Resource
    GeneratorService generatorService;

    /**
     * @param userInfo  用户信息
     * @param page      页数
     * @param size      每页数量
     * @param rangeType 获取的范围类型
     * @param idsStr    id数组字符串，用英文逗号分隔
     * @param buyType   购买类型
     * @return
     * @description 获取购物车商品列表
     * @author maodi
     * @createDate 2018/10/17 13:46
     */
    @GetMapping("shopping/car")
    public ApiResult<Pagination<SimpleCommodityDto>> getShoppingCarCommodityList(
            @FromSession UserInfo userInfo,
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "size", required = false) String size,
            @RequestParam("range_type") String rangeType,
            @RequestParam(value = "ids", required = false) String idsStr,
            @RequestParam(value = "buy_type", required = false) String buyType,
            @RequestParam(value = "user_id", required = false) String userId,
            @RequestParam("user_type") Integer userType) {
        try {
            if (userType == null) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_NULL);
            }
            if (userType != 1 && userType != 2 && userType != 3 && userType != 4) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_ERROR);
            }
            if (userType != 2) {
                if (userInfo == null) {
                    return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
                }
                userId = userInfo.getUserId();
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(rangeType)) {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_NULL);
            }
            if (RangeType.PART.getMessage().equals(rangeType)) {
                if (StringUtils.isBlank(idsStr)) {
                    return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
                }
                String[] ids = idsStr.split(",");
                if (ids == null || ids.length < 1) {
                    return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
                }
                if (StringUtils.isBlank(buyType)) {
                    return ApiResult.fail(ProductErrorCode.BUY_TYPE_IS_NULL);
                }
                int totalCount = geneticTestingOrderCarService.getShoppingCarCommodityCount(userId, userType);
                if ("2".equals(buyType)) {
                    userId = null;
                } else if (!"1".equals(buyType)) {
                    return ApiResult.fail(ProductErrorCode.BUY_TYPE_IS_ERROR);
                }
                Pagination<SimpleCommodityDto> pagination = Pagination.newInstance(LimitHelper.create(1, 10),
                        totalCount);
                List<SimpleCommodityDto> result = geneticTestingOrderCarService.getShoppingCarCommodityListByIds
                        (userId, ids);
                pagination.setResult(result);
                return ApiResult.succ(pagination);
            } else if (RangeType.ALL.getMessage().equals(rangeType)) {
                if (StringUtils.isBlank(page)) {
                    return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
                }
                if (!SimpleStringUtils.isPositiveInteger(page)) {
                    return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
                }
                if (StringUtils.isBlank(size)) {
                    return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
                }
                if (!SimpleStringUtils.isPositiveInteger(size)) {
                    return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
                }
                LimitHelper limitHelper = LimitHelper.create(Integer.valueOf(page), Integer.valueOf(size));
                return ApiResult.succ(geneticTestingOrderCarService.getShoppingCarCommodityList(userId, limitHelper, userType));
            } else {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_ERROR);
            }
        } catch (NumberFormatException e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_LIST_IS_ERROR);
        }
    }

    /**
     * @param geneticTestingOrderCar 购物车信息
     * @param userInfo               用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 新增购物车
     * @author maodi
     * @createDate 2018/10/15 13:44
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PostMapping("shopping/car")
    public ApiResult<NullObject> insertGeneticTestingOrderCar(
            @RequestBody GeneticTestingOrderCar geneticTestingOrderCar,
            @FromSession UserInfo userInfo) {
        try {
            Integer userType = geneticTestingOrderCar.getUserType();
            if (userType == null) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_NULL);
            }
            if (userType != 1 && userType != 2 && userType != 3 && userType != 4) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_ERROR);
            }
            String userId;
            if (userType == 2) {
                userId = geneticTestingOrderCar.getUserId();
            } else {
                if (userInfo == null) {
                    return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
                }
                userId = userInfo.getUserId();
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            geneticTestingOrderCar.setUserId(userId);
            ErrorCode code = checkGeneticTestingOrderCar(geneticTestingOrderCar);
            if (code != null) {
                return ApiResult.fail(code);
            }
            Integer downCount = geneticTestingOrderCarService.queryShelfDownCount(new String[]{geneticTestingOrderCar
                    .getPackageId()});
            if (downCount > 0) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.SHOPPING_CAR_HAS_DOWN_SHELF_STATUS);
            }
            String id = generatorService.generate("", "").getData().getSerialNumber();
            geneticTestingOrderCar.setId(id);
            Date date = new Date();
            geneticTestingOrderCar.setCreateDateTime(date);
            geneticTestingOrderCar.setUpdateDateTime(date);
            geneticTestingOrderCarService.insertGeneticTestingOrderCar(geneticTestingOrderCar);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingOrderCarErrorCode.INSERT_GENETIC_TESTING_ORDER_CAR_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingOrderCarErrorCode.INSERT_GENETIC_TESTING_ORDER_CAR_IS_ERROR);
        }
    }

    /**
     * @param geneticTestingOrderCar 购物车信息
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 校验购物车信息是否规范
     * @author maodi
     * @createDate 2018/10/15 13:41
     */
    private ErrorCode checkGeneticTestingOrderCar(GeneticTestingOrderCar geneticTestingOrderCar) {
        String userId = geneticTestingOrderCar.getUserId();
        if (StringUtils.isBlank(userId)) {
            return CommonErrorCode.USER_ID_IS_NULL;
        }
        //判断商品id是否为空
        String packageId = geneticTestingOrderCar.getPackageId();
        if (StringUtils.isBlank(packageId)) {
            return GeneticTestingOrderCarErrorCode.PACKAGE_ID_IS_NULL;
        }
        //判断数量是否不等于1
        Long amount = geneticTestingOrderCar.getAmount();
        if (amount == null || amount != 1) {
            return GeneticTestingOrderCarErrorCode.AMOUNT_ID_IS_EQUAL_1;
        }
        //根据商品id和用户id去重判断
        int count = geneticTestingOrderCarService.getCountByPackageIdAndUserId(packageId, userId);
        if (count > 0) {
            return GeneticTestingOrderCarErrorCode.GENETIC_TESTING_ORDER_CAR_IS_EXIST;
        }
        //判断勾选是否为空
        Integer checked = geneticTestingOrderCar.getChecked();
        if (checked != null) {
            //判断勾选标识是否为0或1
            if (checked != 0 && checked != 1) {
                return GeneticTestingOrderCarErrorCode.GENETIC_TESTING_ORDER_CAR_CHECKED_IS_ERROR;
            }
        }
        return null;
    }

    /**
     * @param userInfo   用户信息
     * @param id         购物车表主键id
     * @param deleteType 删除类型（0手动删除 1购物车结算删除）
     * @return void
     * @description 根据id删除购物车信息
     * @author maodi
     * @createDate 2018/10/15 10:44
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @DeleteMapping("shopping/car")
    public ApiResult<Pagination<SimpleCommodityDto>> deleteGeneticTestingOrderCar(
            @FromSession UserInfo userInfo,
            @RequestParam("shopping_car_id") String id,
            @RequestParam("delete_type") String deleteType,
            @RequestParam(value = "user_id", required = false) String userId,
            @RequestParam("user_type") Integer userType) {
        try {
            if (userType == null) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_NULL);
            }
            if (userType != 1 && userType != 2 && userType != 3 && userType != 4) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_ERROR);
            }
            if (userType != 2) {
                if (userInfo == null) {
                    return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
                }
                userId = userInfo.getUserId();
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(id)) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.GENETIC_TESTING_ORDER_CAR_ID_IS_NULL);
            }
            if (StringUtils.isBlank(deleteType)) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.DELETE_TYPE_ID_IS_NULL);
            }
            GeneticTestingOrderCar geneticTestingOrderCar = geneticTestingOrderCarService
                    .getGeneticTestingOrderCarById(userId, id);
            if (geneticTestingOrderCar == null || StringUtils.isBlank(geneticTestingOrderCar.getId())) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.HAVE_BEEN_DELETED);
            }
            geneticTestingOrderCarService.deleteGeneticTestingOrderCar(id, Integer.valueOf(deleteType), new Date());
            LimitHelper limitHelper = LimitHelper.create(Integer.valueOf(1), Integer.valueOf(10));
            return ApiResult.succ(geneticTestingOrderCarService.getShoppingCarCommodityList(userId, limitHelper, userType));
        } catch (Exception e) {
            LOGGER.error(GeneticTestingOrderCarErrorCode.DELETE_GENETIC_TESTING_ORDER_CAR_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingOrderCarErrorCode.DELETE_GENETIC_TESTING_ORDER_CAR_IS_ERROR);
        }
    }

    /**
     * @param userInfo 用户信息
     * @param idsStr   购物车信息id数组
     * @param checked  购物车信息勾选状态
     * @return com.hsgene.common.util.result.ApiResult
     * @description 修改购物车信息勾选状态
     * @author maodi
     * @createDate 2018/10/15 14:12
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PutMapping("shopping/car")
    public ApiResult<NullObject> updateChecked(
            @FromSession UserInfo userInfo,
            @RequestParam("shopping_car_ids") String idsStr,
            @RequestParam("checked") String checked) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(idsStr)) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.GENETIC_TESTING_ORDER_CAR_ID_IS_NULL);
            }
            if (StringUtils.isBlank(checked)) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.CHECKED_ID_IS_NULL);
            }
            if (!checked.equals("0") && !checked.equals("1")) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.CHECKED_ID_IS_ERROR);
            }
            String[] ids = idsStr.split(",");
            if (ids == null || ids.length < 1) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.GENETIC_TESTING_ORDER_CAR_ID_IS_NULL);
            }
            geneticTestingOrderCarService.updateCheckedMulti(Integer.valueOf(checked), userId, ids);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingOrderCarErrorCode.UPDATE_GENETIC_TESTING_ORDER_CAR_CHECKED_IS_ERROR.getMessage
                    (), e);
            return ApiResult.fail(GeneticTestingOrderCarErrorCode.UPDATE_GENETIC_TESTING_ORDER_CAR_CHECKED_IS_ERROR);
        }
    }

    @Resource
    CommodityService commodityService;

    /**
     * @param userInfo        用户信息
     * @param confirmOrderDto 确认的订单信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.domain.applets.AppletsOrderSubmitInfoDto>
     * @description 确认小程序购物车订单信息
     * @author maodi
     * @createDate 2018/10/18 12:02
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PostMapping("confirm/order")
    public ApiResult<AppletsOrderSubmitInfoDto> confirmOrder(
            @FromSession UserInfo userInfo,
            @RequestBody ConfirmOrderDto confirmOrderDto) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            ErrorCode code = checkConfirmOrderDto(confirmOrderDto);
            if (code != null) {
                return ApiResult.fail(code);
            }
            Integer downCount = geneticTestingOrderCarService.queryShelfDownCount(confirmOrderDto.getPackageIds());
            if (downCount > 0) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.SHOPPING_CAR_HAS_DOWN_SHELF_STATUS);
            }
            AppletsOrderSubmitInfoDto appletsOrderSubmitInfoDto = addDataToAppletsOrderSubmitInfoDto(userId,
                    confirmOrderDto);
            List<AppletsOrderPackageInfoDto> list = appletsOrderSubmitInfoDto.getPackageInfoDtos();
            if (CollectionUtils.isEmpty(list) || list.size() < 1) {
                return ApiResult.fail(ProductErrorCode.PACKAGE_INFO_IS_ERROR);
            }
            return ApiResult.succ(appletsOrderSubmitInfoDto);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.CONFIRM_ORDER_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.CONFIRM_ORDER_IS_ERROR);
        }
    }

    /**
     * @param userId          用户id
     * @param confirmOrderDto 确认订单的数据
     * @return com.hsgene.order.domain.applets.AppletsOrderSubmitInfoDto
     * @description 添加ConfirmOrderDto数组到AppletsOrderSubmitInfoDto中
     * @author maodi
     * @createDate 2018/10/18 11:36
     */
    private AppletsOrderSubmitInfoDto addDataToAppletsOrderSubmitInfoDto(String userId, ConfirmOrderDto
            confirmOrderDto) {
        AppletsOrderSubmitInfoDto appletsOrderSubmitInfoDto = new AppletsOrderSubmitInfoDto();
        appletsOrderSubmitInfoDto.setConsigneeAddressId(confirmOrderDto.getConsigneeAddressId());
        appletsOrderSubmitInfoDto.setTesterAddressId(confirmOrderDto.getTesterAddressId());
        appletsOrderSubmitInfoDto.setTesterName(confirmOrderDto.getTesterName());
        appletsOrderSubmitInfoDto.setSex(confirmOrderDto.getPatientSex());
        appletsOrderSubmitInfoDto.setEmail(confirmOrderDto.getEmail());
        List<String> testProves = Arrays.asList(confirmOrderDto.getTestingProofImagesUrls());
        List<String> newTestProves = QiniuCertificateUtil.getDownloadCertificateList(testProves);
        appletsOrderSubmitInfoDto.setTestProves(newTestProves);
        appletsOrderSubmitInfoDto.setUserId(userId);
        //购买类型为直接购买则设置userId为null
        if ("2".equals(confirmOrderDto.getBuyType())) {
            userId = null;
        }
        String[] packageIds = confirmOrderDto.getPackageIds();
        List<AppletsOrderPackageInfoDto> packageInfoDtos = commodityService.getAppletsOrderPackageInfoDtosByIds
                (userId, packageIds).getData();
        appletsOrderSubmitInfoDto.setPackageInfoDtos(packageInfoDtos);
        appletsOrderSubmitInfoDto.setDeliveryMethod(confirmOrderDto.getDeliveryMethod());
        appletsOrderSubmitInfoDto.setDiscountId(confirmOrderDto.getUserDiscountId());
        appletsOrderSubmitInfoDto.setInvoiceId(confirmOrderDto.getInvoiceId());
        appletsOrderSubmitInfoDto.setBuyerMessage(confirmOrderDto.getBuyerMessage());
        appletsOrderSubmitInfoDto.setSumPrice(Double.valueOf(confirmOrderDto.getSumPrice()));
        appletsOrderSubmitInfoDto.setDiscountPrice(Double.valueOf(confirmOrderDto.getDiscountPrice()));
        return appletsOrderSubmitInfoDto;
    }

    /**
     * @param confirmOrderDto
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 校验
     * @author maodi
     * @createDate 2018/10/18 9:17
     */
    private ErrorCode checkConfirmOrderDto(ConfirmOrderDto confirmOrderDto) {
        //购买类型是否为空
        String buyType = confirmOrderDto.getBuyType();
        if (StringUtils.isBlank(buyType)) {
            return ProductErrorCode.BUY_TYPE_IS_NULL;
        }
        //判断购买类型是否为1或2
        if (!"1".equals(buyType) && !"2".equals(buyType)) {
            return ProductErrorCode.BUY_TYPE_IS_ERROR;
        }
        //判断收件人地址id是否为空
        String consigneeAddressId = confirmOrderDto.getConsigneeAddressId();
        if (StringUtils.isBlank(consigneeAddressId)) {
            return OrderErrorCode.CONSIGNEE_ADDRESS_ID_IS_NULL;
        }
        //判断检测人地址id是否为空
        String testerAddressId = confirmOrderDto.getTesterAddressId();
        if (StringUtils.isBlank(testerAddressId)) {
            return OrderErrorCode.TESTER_ADDRESS_ID_IS_NULL;
        }
        //判断检测人性别是否为空
        Integer patientSex = confirmOrderDto.getPatientSex();
        if (patientSex == null) {
            return OrderErrorCode.PATIENT_SEX_IS_NULL;
        }
        //判断检测人性别是否为0和1
        if (patientSex != 0 && patientSex != 1) {
            return OrderErrorCode.PATIENT_SEX_IS_ERROR;
        }
        //判断邮箱是否为空
        String email = confirmOrderDto.getEmail();
        if (StringUtils.isBlank(email)) {
            return CommonErrorCode.EMAIL_IS_NULL;
        }
        //判断邮箱是否符合规范
        if (SimpleStringUtils.isEmail(email)) {
            return CommonErrorCode.EMAIL_IS_ERROR;
        }
        //判断证明是否为空
        String[] testingProofImagesUrls = confirmOrderDto.getTestingProofImagesUrls();
        if (testingProofImagesUrls == null || testingProofImagesUrls.length < 1) {
            return OrderErrorCode.TESTING_PROOF_IMAGES_URLS_IS_NULL;
        }
        //判断证明是否超过4张
        if (testingProofImagesUrls.length > 4) {
            return OrderErrorCode.TESTING_PROOF_IMAGES_URLS_EXCEED_4;
        }
        //判断配送方式是否为空
        String deliveryMethod = confirmOrderDto.getDeliveryMethod();
        if (StringUtils.isBlank(deliveryMethod)) {
            return OrderErrorCode.DELIVERY_METHOD_IS_NULL;
        }
        //判断如果有买家留言是否大于200字符
        String buyerMessage = confirmOrderDto.getBuyerMessage();
        if (StringUtils.isNotBlank(buyerMessage)) {
            if (buyerMessage.length() > 200) {
                return OrderErrorCode.BUYER_MESSAGE_EXCEED_200;
            }
        }
        //判断订单总价格是否为空
        String sumPrice = String.valueOf(confirmOrderDto.getSumPrice());
        if (StringUtils.isBlank(sumPrice)) {
            return OrderErrorCode.SUM_PRICE_IS_NULL;
        }
        //判断订单总价格是否为非负数
        if (SimpleStringUtils.isPositiveNumberPattern(sumPrice)) {
            return OrderErrorCode.SUM_PRICE_IS_ERROR;
        }
        String discountPrice = String.valueOf(confirmOrderDto.getDiscountPrice());
        if (StringUtils.isNotBlank(discountPrice)) {
            //判断订单优惠价格是否为非负数
            if (SimpleStringUtils.isPositiveNumberPattern(discountPrice)) {
                return OrderErrorCode.DISCOUNT_PRICE_IS_ERROR;
            }
        }
        return null;
    }

    /**
     * @param userInfo 用户信息
     * @return
     * @description 获取购物车每个商品数量加起来值
     * @author maodi
     * @createDate 2018/10/17 13:46
     */
    @GetMapping("shopping/car/amount")
    public ApiResult<Integer> getShoppingCarCommodityNum(@FromSession UserInfo userInfo, @RequestParam(value =
            "user_id", required = false) String userId, @RequestParam("user_type") Integer userType) {
        try {
            if (userType == null) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_NULL);
            }
            if (userType != 1 && userType != 2 && userType != 3 && userType != 4) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.USER_TYPE_IS_ERROR);
            }
            if (userType != 2) {
                if (userInfo == null) {
                    return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
                }
                userId = userInfo.getUserId();
            }
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            return ApiResult.succ(geneticTestingOrderCarService.getShoppingCarCommodityAmount(userId));
        } catch (NumberFormatException e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_COUNT_BY_USER_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_COUNT_BY_USER_ID_IS_ERROR);
        }
    }

    /**
     * @param idsStr        商品id数组，以英文逗号分隔
     * @param isShoppingCar 是否从购物车购买(0-否，1-是)
     * @param userInfo      用户信息
     * @return com.hsgene.common.util.result.ApiResult<java.util.List<com.hsgene.coupon.dto.GeneticDiscountDto>>
     * @description 查询购物车优惠券
     * @author maodi
     * @createDate 2018/11/15 15:24
     */
    @GetMapping("shopping/car/discounts")
    public ApiResult<List<GeneticUserDiscountDto>> getShoppingCarDiscounts(
            @RequestParam("ids") String idsStr,
            @RequestParam("isShoppingCar") String isShoppingCar,
            @FromSession UserInfo userInfo) {
        try {
            if (StringUtils.isBlank(idsStr)) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            String[] ids = idsStr.split(",");
            if (ids == null || ids.length < 1) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (!"0".equals(isShoppingCar) && !"1".equals(isShoppingCar)) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.IS_SHOPPING_CAR_ID_IS_ERROR);
            }
            return ApiResult.succ(geneticTestingOrderCarService.getShoppingCarDiscounts(userId, ids, isShoppingCar));
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.QUERY_SHOPPING_CAR_DISCOUNTS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.QUERY_SHOPPING_CAR_DISCOUNTS_IS_ERROR);
        }

    }

    /**
     * @param idsStr        商品id数组字符串，用英文逗号分隔
     * @param discountId    优惠券id
     * @param isShoppingCar 是否是购物车结算(0-否[立即购买],1-是[购物车购买])
     * @param userInfo      用户信息
     * @return
     * @description 根据id数组获取购物车商品结算信息
     * @author maodi
     * @createDate 2018/10/17 15:09
     */
    @GetMapping("shopping/car/balance")
    public ApiResult<Map<String, Object>> getShoppingCarCommodityBalanceByIds(
            @RequestParam("ids") String idsStr,
            @RequestParam(name = "discountId", required = false) String discountId,
            @RequestParam(name = "isShoppingCar", defaultValue = "0") Integer isShoppingCar,
            @FromSession UserInfo userInfo) {
        try {
            if (StringUtils.isBlank(idsStr)) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            String[] ids = idsStr.split(",");
            if (ids == null || ids.length < 1) {
                return ApiResult.fail(ProductErrorCode.COMMODITY_IDS_IS_NULL);
            }
            if (isShoppingCar != 0 && isShoppingCar != 1) {
                return ApiResult.fail(ProductErrorCode.IS_SHOPPING_CAR_IS_ERROR);
            }
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            Integer downCount = geneticTestingOrderCarService.queryShelfDownCount(ids);
            if (downCount > 0) {
                return ApiResult.fail(GeneticTestingOrderCarErrorCode.SHOPPING_CAR_HAS_DOWN_SHELF_STATUS);
            }
            Map<String, Object> balance = geneticTestingOrderCarService.getShoppingCarCommodityBalanceByIds(userId,
                    ids, isShoppingCar.toString());
            double originPrice = Double.valueOf(String.format("%.2f", balance.get("originPrice")));
            Double discount = 0.00;
            if (StringUtils.isNotBlank(discountId)) {
                DiscountDto discountDto = geneticTestingOrderCarService.queryDiscountInfo(discountId, originPrice,
                        userId);
                if (discountDto != null) {
                    Double conditionPrice = discountDto.getConditionPrice() == null ? 0.00 : discountDto
                            .getConditionPrice();
                    if (originPrice <= conditionPrice) {
                        return ApiResult.fail(ProductErrorCode.DISCOUNT_IS_ERROR);
                    }
                    discount = discountDto.getDiscountPrice() == null ? 0.00 : discountDto.getDiscountPrice();
                    discount = Double.valueOf(String.format("%.2f", discount));
                }
            }
            double showPrice = Double.valueOf(String.format("%.2f", balance.get("showPrice"))) - discount;
            double discountPrice = Double.valueOf(String.format("%.2f", balance.get("discountPrice"))) + discount;
            balance.put("originPrice", originPrice);
            balance.put("showPrice", Double.valueOf(String.format("%.2f", showPrice)));
            balance.put("discountPrice", Double.valueOf(String.format("%.2f", discountPrice)));
            return ApiResult.succ(balance);
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_BALANCE_BY_IDS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.GET_SHOPPING_CAR_COMMODITY_BALANCE_BY_IDS_IS_ERROR);
        }
    }

}
